﻿using GalaSoft.MvvmLight.CommandWpf;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Media;
using System.Windows.Threading;

namespace Demo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private NotifyIcon TrayIcon;
        WindowState ws;
        WindowState wsl;

        DispatcherTimer icoTimer = new DispatcherTimer();
 
        public long i = 0;
        private System.Windows.Forms.ContextMenu notifyiconMnu;
        public MainWindow()
        {
            InitializeComponent();
            Initializenotifyicon();
            //保证窗体显示在上方。
            wsl = WindowState;
            ShowInTaskbar = false;

            this.DataContext = this;
            friendGroups = new ObservableCollection<CustomFriendGroup>();
            var g1 = new CustomFriendGroup() { Name = "同学", Id = 1 };
            var g2 = new CustomFriendGroup() { Name = "同事", Id = 2 };
            var g3 = new CustomFriendGroup() { Name = "朋友", Id = 3 };
            g1.AddData(new FriendEntity() {Name = "小明", Uid = 1, Gid = g1.Id ,HeadImage = "Resources/1.png"});
            g1.AddData(new FriendEntity() {Name = "小红", Uid = 2, Gid = g1.Id, HeadImage = "Resources/2.png" });

            g2.AddData(new FriendEntity() { Name = "李冰", Uid = 3, Gid = g2.Id, HeadImage = "Resources/3.png" });
            g2.AddData(new FriendEntity() { Name = "王明", Uid = 4, Gid = g2.Id, HeadImage = "Resources/4.png" });

            g3.AddData(new FriendEntity() { Name = "李冰", Uid = 5, Gid = g3.Id, HeadImage = "Resources/5.png" });
            g3.AddData(new FriendEntity() { Name = "王明", Uid = 6, Gid = g3.Id, HeadImage = "Resources/6.png" });

            friendGroups.Add(g1);
            friendGroups.Add(g2);
            friendGroups.Add(g3);



        }
        private void OnNotifyIconDoubleClick(object sender, EventArgs e)
        {
            this.Show();
            WindowState = wsl;
        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            ws = WindowState;
            if (ws == WindowState.Minimized)
            {
                this.Hide();
            }
        }
        public void TopAllmost(object sender, System.EventArgs e)
        {
            try
            {
                this.Visibility = System.Windows.Visibility.Visible;
                this.ShowInTaskbar = true;
                System.Windows.Forms.MenuItem item = (System.Windows.Forms.MenuItem)sender;
                bool check = item.Checked;
                item.Checked = !check;
                this.Topmost = item.Checked;

                this.Activate();
            }
            catch
            {
            }
        }


        public void ExitSelect(object sender, System.EventArgs e)
        {
            TrayIcon.Visible = false;
            this.Close();
        }
        private void Initializenotifyicon()
        {
            Assembly assem = Assembly.GetExecutingAssembly();
            Stream stream = assem.GetManifestResourceStream(
             "Tray.ico");

            TrayIcon = new NotifyIcon();
            TrayIcon.Icon = new System.Drawing.Icon("Tray.ico");//程序图标
            this.TrayIcon.BalloonTipText = "Hello, 文件监视器"; //设置程序启动时显示的文本
            TrayIcon.Text = "MutiMenu " + "Copyright: Frank Zhao";
            TrayIcon.Visible = true;
            TrayIcon.MouseDoubleClick += OnNotifyIconDoubleClick;
            this.TrayIcon.ShowBalloonTip(1000);
            //  TrayIcon.Click += new System.EventHandler(this.click);

            //tray menu
            System.Windows.Forms.MenuItem[] mnuItms = new System.Windows.Forms.MenuItem[5];
            mnuItms[0] = new System.Windows.Forms.MenuItem();
            mnuItms[0].Text = "Aways Top";
            mnuItms[0].Click += new System.EventHandler(this.TopAllmost);
            mnuItms[0].Checked = true;

            mnuItms[1] = new System.Windows.Forms.MenuItem("-");

            mnuItms[2] = new System.Windows.Forms.MenuItem();
            mnuItms[2].Text = "Settings...";
          //  mnuItms[2].Click += new System.EventHandler(this.Settings);

            mnuItms[3] = new System.Windows.Forms.MenuItem("-");

            mnuItms[4] = new System.Windows.Forms.MenuItem();
            mnuItms[4].Text = "Exit";
            mnuItms[4].Click += new System.EventHandler(this.ExitSelect);
            mnuItms[4].DefaultItem = true;


            notifyiconMnu = new System.Windows.Forms.ContextMenu(mnuItms);
            TrayIcon.ContextMenu = notifyiconMnu;
        }
        public void IcoTimer_Tick(object sender, EventArgs e)
        {
            i = i + 1;
            if (i % 2 != 0)
            {
                this.TrayIcon.Icon = new System.Drawing.Icon("Tray.ico");

                
            }
            else
            {
                this.TrayIcon.Icon = new System.Drawing.Icon("Xray.ico");
            }

            if(friendGroups[0].Friends[0].HeadImage == "Resources/1.png")
            {
                friendGroups[0].Friends[0].HeadImage = "Resources/blank.png";
            }
            else
            {
                friendGroups[0].Friends[0].HeadImage = "Resources/1.png";
            }
        }
        private childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(obj, i);
                if (child != null && child is childItem)
                    return (childItem)child;
                else
                {
                    childItem childOfChild = FindVisualChild<childItem>(child);
                    if (childOfChild != null)
                        return childOfChild;
                }
            }
            return null;
        }
        private void btnStart_Click(object sender, RoutedEventArgs e)
        {

            //foreach (var item in myListBox.Items)
            //{
            //    var myListBoxItem = (myListBox.ItemContainerGenerator.ContainerFromItem(item));
            //    ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);
            //    DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
            //    System.Windows.Controls.ItemsControl gifImage = (System.Windows.Controls.ItemsControl)myDataTemplate.FindName("lb2", myContentPresenter);

            //    int a = 5;

            //}


            // WindowExtensions.FlashWindow(this, 55, 500);
            this.Activate();
            //闪烁图标
            icoTimer.Interval = TimeSpan.FromSeconds(0.3);
            icoTimer.Tick += new EventHandler(IcoTimer_Tick);
            icoTimer.Start();
            TrayIcon.BalloonTipText = "定时器看，开启"; //设置程序启动时显示的文本
            this.TrayIcon.ShowBalloonTip(1000);

        

        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            this.StopFlashingWindow();
            icoTimer.Stop();
            TrayIcon.BalloonTipText = "定时器看，关闭"; //设置程序启动时显示的文本
            this.TrayIcon.ShowBalloonTip(1000);
        }


        public ObservableCollection<CustomFriendGroup> friendGroups
        {
            get
            {
                return _friends;
            }
            set
            {
                _friends = value;
                RaisePropertyChanged("FriendGroup");
            }
        }
        private ObservableCollection<CustomFriendGroup> _friends { get; set; }
        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
        #region Methods
        private void RaisePropertyChanged(string propertyName)
        {
            // take a copy to prevent thread issues
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion


        private int selectIndex = -1;

        public int SelectIndex
        {
            get { return selectIndex; }
            set
            {
                selectIndex = value;
                RaisePropertyChanged("SelectIndex");
                //ViewModelLocator.DialogService.ShowInfoDialog($"您当前选择的是：{selValue}");
            }
        }


        private int frdselectIndex = -1;

        public int FrdselectIndex
        {
            get { return frdselectIndex; }
            set
            {
                frdselectIndex = value;
                RaisePropertyChanged("FrdselectIndex");
                //ViewModelLocator.DialogService.ShowInfoDialog($"您当前选择的是：{selValue}");
            }
        }
        private RelayCommand<SelectionChangedEventArgs> selectionChangedCommand;

        public RelayCommand<SelectionChangedEventArgs> SelectionChangedCommand
        {
            get
            {
                if (selectionChangedCommand == null)
                {
                    selectionChangedCommand = new RelayCommand<SelectionChangedEventArgs>(SelectChange);
                }
                return selectionChangedCommand;
            }
            set { selectionChangedCommand = value; }
        }


        private void SelectChange(SelectionChangedEventArgs e)//当导航多次切换时候，会触发多次，好奇怪
        {
            //int i = 0;
            //foreach (var a in friendGroups[SelectIndex].Friends)
            //{
            //    if (i == FrdselectIndex)
            //    {
            //        string selResult = (a as FriendGroup).Name;
            //        System.Windows.MessageBox.Show(selResult);
            //        break;
            //    }
            //    i++;
            //}

            string groupName = friendGroups[SelectIndex].Name;
            string friendName = friendGroups[SelectIndex].Friends[FrdselectIndex].Name;
            System.Windows.MessageBox.Show($"{groupName} + {friendName}");
        }




        private RelayCommand<object> mouseDoubleClickCommand;

        public RelayCommand<object> MouseDoubleClickCommand
        {
            get
            {
                if (mouseDoubleClickCommand == null)
                {
                    mouseDoubleClickCommand = new RelayCommand<object>(Label_MouseDoubleClick);
                }
                return mouseDoubleClickCommand;
            }
            set { mouseDoubleClickCommand = value; }
        }

        
        private void Label_MouseDoubleClick(object e)
        {
            System.Windows.MessageBox.Show("dd");
        }

        private void Label_MouseDoubleClick_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            FriendEntity fd = (sender as System.Windows.Controls.Label).DataContext as FriendEntity;


            System.Windows.MessageBox.Show($"{fd.Gid} + {fd.Uid} + {fd.Name}");
        }

        private void muDelete_Click(object sender, RoutedEventArgs e)
        {
            int a = 4;
            FriendEntity fd = (e.Source as System.Windows.Controls.MenuItem).DataContext as FriendEntity;

            friendGroups[fd.Gid - 1].Friends.Remove(fd);
        }

        private void muAddCatelog_Click(object sender, RoutedEventArgs e)
        {
            var fg = new CustomFriendGroup();
            fg.Name = "新组";
            friendGroups.Add(fg);
        }
    }


    public class FriendEntity : INotifyPropertyChanged
    {
        public int Uid { get; set; }
        public int Gid { get; set; }
        public string Name { get; set; }

        private string headImage;
        public string HeadImage
        {
            get { return headImage; }
            set
            {
                headImage = value;
                RaisePropertyChanged("HeadImage");
            }

         
        }

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
        #region Methods
        private void RaisePropertyChanged(string propertyName)
        {
            // take a copy to prevent thread issues
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }


    public class FriendGroup : INotifyPropertyChanged
    {
        public String Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
                RaisePropertyChanged("Name");
            }
        }
        private String _name { get; set; }

        public int Id
        {
            get; set;
        }

        public FriendGroup()
        {
            Friends = new ObservableCollection<FriendEntity>();
        

        }
        public void AddData(FriendEntity data)
        {
            Friends.Add(data);

        }

        public ObservableCollection<FriendEntity> Friends
        {
            get
            {
                return _friends;
            }
            set
            {
                _friends = value;
                RaisePropertyChanged("Friends");
            }
        }
        private ObservableCollection<FriendEntity> _friends { get; set; }


        #region INotifyPropertyChanged Members



        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
        #region Methods
        private void RaisePropertyChanged(string propertyName)
        {
            // take a copy to prevent thread issues
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }


    public class CustomFriendGroup : INotifyPropertyChanged
    {
        public String Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
                RaisePropertyChanged("Name");
            }
        }
        private String _name { get; set; }

        public int Id
        {
            get; set;
        }

        public CustomFriendGroup()
        {
            Friends = new ObservableCollection<FriendEntity>();


        }
        public void AddData(FriendEntity data)
        {
            Friends.Add(data);

        }

        public ObservableCollection<FriendEntity> Friends
        {
            get
            {
                return _friends;
            }
            set
            {
                _friends = value;
                RaisePropertyChanged("Friends");
            }
        }
        private ObservableCollection<FriendEntity> _friends { get; set; }


        #region INotifyPropertyChanged Members



        public event PropertyChangedEventHandler PropertyChanged;

        #endregion
        #region Methods
        private void RaisePropertyChanged(string propertyName)
        {
            // take a copy to prevent thread issues
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }
}
